import { InjectRedis } from '@liaoliaots/nestjs-redis'
import { Redis } from 'ioredis'

export class RedisService {
  constructor(@InjectRedis() private readonly client: Redis) {}
  /* --------------------- string 相关 -------------------------- */
  /**
   * 返回对应的 value
   * @param {string} key
   */
  async get(key: string): Promise<any> {
    if (!key || key === '*') return null
    const res = await this.client.get(key)
    return JSON.parse(res)
  }
  /**
   *
   * @param key 存储 key 值
   * @param val key 对应的 val
   * @param ttl 可选，过期时间，单位 毫秒
   */
  async set(key: string, val: any, ttl?: number): Promise<'OK' | null> {
    const data = JSON.stringify(val)
    if (!ttl) return await this.client.set(key, data)
    return await this.client.set(key, data, 'PX', ttl)
  }
  /* --------------------- end string 相关 -------------------------- */
}
